﻿#-*- coding: utf-8 -*-
'''
	Torrenter plugin for XBMC
	Copyright (C) 2011 Vadim Skorba
	vadim.skorba@gmail.com

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

import Downloader
import Localization
import sys
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
import urllib
import urllib2
import re
import tempfile
import time
import cookielib
import json
import xml.dom.minidom
import os.path

class Core:
	__plugin__ = sys.modules[ "__main__"].__plugin__
	__settings__ = sys.modules[ "__main__" ].__settings__
	ROOT = sys.modules[ "__main__"].__root__
	userStorageDirectory = __settings__.getSetting("storage")
	USERAGENT = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0"
	URL = 'http://xbmctorrenter.0fees.net'
	torrentFilesDirectory = 'torrents'
	htmlCodes = (
		('&', '&amp;'),
		('<', '&lt;'),
		('>', '&gt;'),
		('"', '&quot;'),
		("'", '&#39;'),
	)
	stripPairs = (
		('<p>', '\n'),
		('<li>', '\n'),
		('<br>', '\n'),
		('<.+?>', ' '),
		('</.+?>', ' '),
		('&nbsp;', ' '),
	)
	skinOptimizations = (
		{#Confluence
			'list': 50,
			'info': 50,
			'wide': 51,
			'icons': 500,
		},
		{#Transperency!
			'list': 50,
			'info': 51,
			'wide': 52,
			'icons': 53,
		}
	)

	def __init__(self):
		if 0 == len(self.userStorageDirectory):
			self.userStorageDirectory = tempfile.gettempdir() + os.path.sep + 'Torrenter'
		else:
			self.userStorageDirectory = self.userStorageDirectory + 'Torrenter'

	def forceUpdate(self):
		'''try:
			from sqlite3 import dbapi2 as sqlite
			print "Loading sqlite3 as DB engine"
		except:
			from pysqlite2 import dbapi2 as sqlite
			print "Loading pysqlite2 as DB engine"
		DB = os.path.join(xbmc.translatePath("special://database"), 'Addons15.db')
		db = sqlite.connect(DB)
		db.execute('DELETE FROM repo WHERE addonID="plugin.video.torrenter"')
		db.execute('DELETE FROM addon WHERE name="Torrenter"')
		db.commit()
		db.close()'''

	def drawItem(self, title, action, link = '', image=None, isFolder = True, contextMenu=None):
		listitem = xbmcgui.ListItem(title, iconImage=image, thumbnailImage=image)
		url = '%s?action=%s&url=%s' % (sys.argv[0], action, urllib.quote_plus(link))
		if contextMenu:
			listitem.addContextMenuItems(contextMenu, replaceItems=True)
		if isFolder:
			listitem.setProperty("Folder", "true")
		else:
			listitem.setInfo(type = 'Video', infoLabels = {"Title":title})
		xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=isFolder)

	def fetchData(self, url, referer = None):
		request = urllib2.Request(url)
		if referer != None:
			request.add_header('Referer', referer)
		request.add_header('User-Agent', self.USERAGENT)
		if self.__settings__.getSetting("auth"):
			authString = '; ' + self.__settings__.getSetting("auth")
		else:
			authString = ''
		request.add_header('Cookie', authString)
		try:
			connection = urllib2.urlopen(request)
			result = connection.read()
			connection.close()
			return (result)
		except (urllib2.HTTPError, urllib2.URLError) as e:
			print self.__plugin__ + " fetchData(" + url + ") exception: " + str(e)
			return

	def lockView(self, viewId):
		if 'true' == self.__settings__.getSetting("lock_view"):
			try:
				xbmc.executebuiltin("Container.SetViewMode(%s)" % str(self.skinOptimizations[int(self.__settings__.getSetting("skin_optimization"))][viewId]))
			except:
				return

	def getParameters(self, parameterString):
		commands = {}
		splitCommands = parameterString[parameterString.find('?')+1:].split('&')
		for command in splitCommands: 
			if (len(command) > 0):
				splitCommand = command.split('=')
				name = splitCommand[0]
				value = splitCommand[1]
				commands[name] = value
		return commands

	def unescape(self, string):
		for (symbol, code) in self.htmlCodes:
			string = re.sub(code, symbol, string)
		return string

	def stripHtml(self, string):
		for (html, replacement) in self.stripPairs:
			string = re.sub(html, replacement, string)
		return string
		
	def executeAction(self, params = {}):
		get = params.get
		if hasattr(self, get("action")):
			getattr(self, get("action"))(params)
		else:
			self.sectionMenu()

	def clearStorage(self, params = {}):
		if os.path.exists(self.userStorageDirectory):
			import shutil
			shutil.rmtree(self.userStorageDirectory, ignore_errors=True)
		xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Storage'), Localization.localize('Storage was cleared')))

	def playTorrent(self, params = {}):
		torrentUrl = self.__settings__.getSetting("lastTorrent")
		if 0 != len(torrentUrl):
			get = params.get
			contentId = int(urllib.unquote_plus(get("url")))
			torrent = Downloader.Torrent(self.userStorageDirectory, torrentUrl, self.torrentFilesDirectory)
			torrent.startSession(contentId)
			iterator = 0
			progressBar = xbmcgui.DialogProgress()
			progressBar.create(Localization.localize('Please Wait'), Localization.localize('Seeds searching.'))
			while not torrent.canPlay:
				time.sleep(1)
				if os.path.exists(torrent.getFilePath(contentId)):
					progressBar.update(iterator, Localization.localize('Seeds searching.'), Localization.localize('Preloaded: ') + str(os.path.getsize(torrent.getFilePath(contentId)) / 1024 / 1024) + ' MB / ' + str(torrent.getFileSize(contentId) / 1024 / 1024) + ' MB')
				else:
					progressBar.update(iterator, Localization.localize('Seeds searching.'), Localization.localize('Preloaded: ') + '0 MB / ' + str(torrent.getFileSize(contentId) / 1024 / 1024) + ' MB')
				iterator += 10
				if iterator == 100:
					iterator = 0
				if progressBar.iscanceled():
					progressBar.update(0)
					progressBar.close()
					return
			self.forceUpdate()
			progressBar.update(0)
			progressBar.close()
			playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
			playlist.clear()
			listitem = xbmcgui.ListItem(torrent.getContentList()[contentId].path)
			playlist.add(torrent.getFilePath(contentId), listitem)
			xbmc.Player().play(playlist)
			if 0 < len(self.__settings__.getSetting("auth")):
				self.fetchData(self.URL + '/history/add?link=%s&name=%s' % (urllib.quote_plus(self.__settings__.getSetting("lastTorrentUrl")), urllib.quote_plus(torrent.getContentList()[contentId].path)))
			while 1 == xbmc.Player().isPlayingVideo():
				torrent.fetchParts()
				torrent.checkThread()
				time.sleep(1)
			if 'true' == self.__settings__.getSetting("clear_storage"):
				torrent.threadComplete = True
				self.clearStorage()
			else:
				dialog = xbmcgui.Dialog()
				if dialog.yesno(
					Localization.localize('Torrent Downloading'),
					Localization.localize('Do you want to STOP current torrent downloading?'),
					Localization.localize('Preloaded: ') + str(os.path.getsize(torrent.getFilePath(contentId)) / 1024 / 1024) + ' MB / ' + str(torrent.getFileSize(contentId) / 1024 / 1024) + ' MB'
				):
					xbmc.executebuiltin("Notification(%s, %s)" % (Localization.localize('Information'), Localization.localize('Torrent downloading is stopped.')))
					torrent.threadComplete = True
		else:
			print self.__plugin__ + " Unexpected access to method playTorrent() without torrent content"

	def openTorrent(self, params = {}):
		get = params.get
		url = urllib.unquote_plus(get("url"))
		self.__settings__.setSetting("lastTorrentUrl", url)
		torrent = Downloader.Torrent(self.userStorageDirectory, torrentFilesDirectory = self.torrentFilesDirectory)
		if re.match("^magnet\:.+$", url):
			torrent.magnetToTorrent(url)
		else:
			torrent.saveTorrent(url)
		if os.path.exists(str(torrent.torrentFile)):
			self.__settings__.setSetting("lastTorrent", torrent.torrentFile)
			contentId = 0
			listitem = xbmcgui.ListItem('<' + Localization.localize('Add To Bookmarks') + ' >')
			itemUrl = '%s?action=%s&url=%s&name=%s&seeds=%s&image=%s' % (sys.argv[0], 'addBookmark', urllib.quote_plus(url), urllib.quote_plus(torrent.getContentList()[0].path), 0, '')
			listitem.setInfo(type = 'Video', infoLabels = {"Title":'<' + Localization.localize('Add To Bookmarks') + ' >'})
			xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=itemUrl, listitem=listitem)
			for contentFile in torrent.getContentList():
				fileTitle = "%s [%s MB]" % (contentFile.path, contentFile.size / 1024 / 1024)#In MB
				self.drawItem(self.unescape(fileTitle), 'playTorrent', str(contentId), isFolder=False)
				contentId += 1
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentPlaybleRu(self, params = {}):
		address = 'http://playble.ru/search/video/~rss'
		document = xml.dom.minidom.parse(urllib.urlopen(address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
			description = item.getElementsByTagName('description')[0].firstChild.data.encode('utf-8', 'replace')
			#seeds = re.search("<span class=\"s\">(\d+)</span>", description).group(1)
			image = re.search("<img src=\"(.+?)\" alt=\"\" />", description).group(1)
			self.drawItem(title, 'openSection', title, image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentRuTorOrg(self, params = {}):
		categories = [1, 5, 12, 4, 6, 7, 10, 13, 15]
		for category in  categories:
			address = 'http://rutor.org/rss.php?category=' + str(category)
			document = xml.dom.minidom.parse(urllib.urlopen(address))
			for item in document.getElementsByTagName('item'):
				title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
				link = item.getElementsByTagName('link')[0].firstChild.data
				image = self.ROOT + '/icons/video.png'
				link = 'http://d.rutor.org/download.php?rss=' + re.search('^.+\/(\d+)$', link).group(1)
				self.drawItem(title, 'openTorrent', link, image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentRuTrackerOrg(self, params = {}):
		address = 'http://xpoft.ru/torrents.ru/rss.xml?352;93;101;905;100;2198;313;2199;312;33;124;149;7;187;2459;212;2221;2091;2092;2093;2090;921;4;2365;930;208;1900;539;822;22;941;789;772'
		document = xml.dom.minidom.parse(urllib.urlopen(address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
			description = item.getElementsByTagName('description')[0].firstChild.data.encode('utf-8', 'replace')
			try:
				image = re.search("<img src=\"(.+?)\">", self.unescape(description)).group(1)
			except:
				image = self.ROOT + '/icons/video.png'
			self.drawItem(title, 'openSection', title, image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentKinopoiskRuBluRay(self, params = {}):
		address = 'http://st.kinopoisk.ru/rss/bluray.rss'
		document = xml.dom.minidom.parse(urllib.urlopen(address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
			try:
				image = item.getElementsByTagName('enclosure')[0].attributes.get('url').nodeValue
			except:
				image = self.ROOT + '/icons/video.png'
			self.drawItem(title, 'openSection', re.search('^Blu-Ray\:\s(.+)$', title).group(1), image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentKinopoiskRuDvd(self, params = {}):
		address = 'http://st.kinopoisk.ru/rss/dvd.rss'
		document = xml.dom.minidom.parse(urllib.urlopen(address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
			try:
				image = item.getElementsByTagName('enclosure')[0].attributes.get('url').nodeValue
			except:
				image = self.ROOT + '/icons/video.png'
			self.drawItem(title, 'openSection', re.search('^DVD\:\s(.+)$', title).group(1), image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentKinopoiskRu(self, params = {}):
		address = 'http://st.kinopoisk.ru/rss/premiere.rss'
		document = xml.dom.minidom.parse(urllib.urlopen(address))
		for item in document.getElementsByTagName('item'):
			title = item.getElementsByTagName('title')[0].firstChild.data.encode('utf-8', 'replace')
			image =  item.getElementsByTagName('enclosure')[0].attributes.get('url').nodeValue
			self.drawItem(title, 'openSection', title, image)
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def recentMaterilas(self, params = {}):
		self.drawItem('RuTracker.Org', 'recentRuTrackerOrg')
		self.drawItem('RuTor.Org', 'recentRuTorOrg')
		self.drawItem('Playble.Ru', 'recentPlaybleRu')
		self.drawItem('Kinopoisk.Ru', 'recentKinopoiskRu')
		self.drawItem('Kinopoisk.Ru - DVD', 'recentKinopoiskRuDvd')
		self.drawItem('Kinopoisk.Ru - Blu-Ray', 'recentKinopoiskRuBluRay')
		self.lockView('info')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def sectionMenu(self):
		self.drawItem(Localization.localize('< Search >'), 'search', image=self.ROOT + '/icons/search.png')
		self.drawItem(Localization.localize('< Recent Materials >'), 'recentMaterilas', image=self.ROOT + '/icons/video.png')
		if self.__settings__.getSetting("auth"):
			self.drawItem(Localization.localize('< Bookmarks >'), 'getBookmarks', image=self.ROOT + '/icons/bookmarks.png')
			self.drawItem(Localization.localize('< History >'), 'getHistory', image=self.ROOT + '/icons/history.png')
			self.drawItem(Localization.localize('< Logout >'), 'logoutUser', image=self.ROOT + '/icons/logout.png')
		else:
			self.drawItem(Localization.localize('< Login >'), 'loginUser', image=self.ROOT + '/icons/login.png')
			self.drawItem(Localization.localize('< Register >'), 'registerUser', image=self.ROOT + '/icons/register.png')
		if 'false' == self.__settings__.getSetting("clear_storage"):
			self.drawItem(Localization.localize('< Clear Storage >'), 'clearStorage', isFolder = True)
		self.lockView('list')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def openSection(self, params = {}):
		get = params.get
		url = urllib.unquote_plus(get("url"))
		filesList = []
		progressBar = xbmcgui.DialogProgress()
		progressBar.create(Localization.localize('Please Wait'), Localization.localize('Materials are loading now.'))
		iterator = 0
		searchersList = []
		dirList = os.listdir(self.ROOT + '/resources/searchers')
		for searcherFile in dirList:
			if re.match('^(\w+)\.py$', searcherFile):
				searchersList.append(searcherFile)
		for searcherFile in searchersList:
			searcher = re.search('^(\w+)\.py$', searcherFile).group(1)
			if searcher:
				progressBar.update(int(iterator), searcher)
				filesList += self.searchWithSearcher(url, searcher)
				iterator += 100 / len(searchersList)
			if progressBar.iscanceled():
				progressBar.update(0)
				progressBar.close()
				return
		progressBar.update(0)
		progressBar.close()
		filesList = sorted(filesList, key=lambda x: x[0], reverse=True)
		self.showFilesList(filesList)

	def searchWithSearcher(self, keyword, searcher):
		filesList = []
		if self.ROOT + '/resources/searchers' not in sys.path:
			sys.path.insert(0, self.ROOT + '/resources/searchers')
		searcherModule = __import__(searcher)
		try:
			searchRequestUrl = getattr(searcherModule, 'searchRequestUrl')
			searchRegularExpression = getattr(searcherModule, 'searchRegularExpression')
			searchIcon = getattr(searcherModule, 'searchIcon')
			isMagnetLinkSource = getattr(searcherModule, 'isMagnetLinkSource')
			sourceWeight = getattr(searcherModule, 'sourceWeight')
		except Exception, e:
			print 'Unable to use searcher: ' + searcher + ' at ' + self.__plugin__ + 'searchWithSearcher(). Exception: ' + str(e)
			return filesList
		if isMagnetLinkSource and 'false' == self.__settings__.getSetting("use_magnet_links"):
			return filesList
		torrentsLink = searchRequestUrl % (urllib.quote_plus(keyword))
		videos = self.fetchData(torrentsLink, torrentsLink)
		if 0 < len(videos):
			for (title, link, seeds) in re.compile(searchRegularExpression, re.DOTALL).findall(videos):
				torrentTitle = "%s [%s: %s]" % (title, Localization.localize('Seeds'), seeds)
				image = self.ROOT + searchIcon
				filesList.append((
		            int(int(sourceWeight) * int(seeds)),
		            int(seeds),
		            self.unescape(self.stripHtml(torrentTitle)),
		            link,
		            image,
		        ))
		return filesList

	def showFilesList(self, filesList):
		for (order, seeds, title, link, image) in filesList:
			contextMenu = [(
				Localization.localize('Add To Bookmarks'),
				'XBMC.RunPlugin(%s)' % ('%s?action=%s&url=%s&name=%s&seeds=%s&image=%s') % (sys.argv[0], 'addBookmark', urllib.quote_plus(link), urllib.quote_plus(title), seeds, urllib.quote_plus(image))
			)]
			self.drawItem(title, 'openTorrent', link, image, contextMenu=contextMenu)
		self.lockView('wide')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def getHistory(self, params = {}):
		filesList = []
		response = json.loads(self.fetchData(self.URL + '/history').split("\n")[0])
		if not self.checkForAuth(response):
			return
		for record in response:
			filesList.append((0, 0, str(record['name'].encode('utf-8', 'replace')), record['link'], ''))
		self.showFilesList(filesList)
	
	def getBookmarks(self, params = {}):
		response = json.loads(self.fetchData(self.URL + '/bookmarks').split("\n")[0])
		if not self.checkForAuth(response):
			return
		for record in response:
			contextMenu = [(
				Localization.localize('Remove From Bookmarks'),
				'XBMC.RunPlugin(%s)' % ('%s?action=%s&id=%s') % (sys.argv[0], 'removeBookmark', record['id'])
			)]
			self.drawItem(str(record['name'].encode('utf-8', 'replace')), 'openTorrent', record['link'], record['image'], contextMenu=contextMenu)
		self.lockView('wide')
		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=True)

	def removeBookmark(self, params = {}):
		get = params.get
		response = json.loads(self.fetchData(self.URL + '/bookmarks/remove?id=%s' % (get("id"))).split("\n")[0])
		if not self.checkForAuth(response):
			return
		if 'removed' == response:
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Item successfully removed from Bookmarks')))
			xbmc.executebuiltin("Container.Refresh()")
		else:
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Bookmark not removed')))

	def addBookmark(self, params = {}):
		get = params.get
		response = json.loads(self.fetchData(self.URL + '/bookmarks/add?link=%s&name=%s&seeds=%s&image=%s' % (get("url"), get('name'), get('seeds'), get('image'))).split("\n")[0])
		if not self.checkForAuth(response):
			return
		if 'added' == response:
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Item successfully added to Bookmarks')))
		else:
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Bookmark'), Localization.localize('Bookmark not added')))

	def search(self, params = {}):
		defaultKeyword = params.get('url')
		keyboard = xbmc.Keyboard(defaultKeyword, Localization.localize('Search Phrase') + ':')
		keyboard.doModal()
		query = keyboard.getText()
		if not query:
			return
		elif keyboard.isConfirmed():
			params["url"] = urllib.quote_plus(query)
			self.openSection(params)

	def loginUser(self, params = {}):
		if self.__settings__.getSetting("auth"):
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Already logged in')))
			return

		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=False)
		keyboardUser = xbmc.Keyboard("", Localization.localize("Input Email:"))
		keyboardUser.doModal()
		email = keyboardUser.getText()
		if not email:
			return

		keyboardPass = xbmc.Keyboard("", Localization.localize("Input Password:"))
		keyboardPass.setHiddenInput(True)
		keyboardPass.doModal()
		password = keyboardPass.getText()
		keyboardPass.setHiddenInput(False)
		if not password:
			return
		try:
			cookieJar = cookielib.CookieJar()
			opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
			value = json.loads(opener.open(self.URL + "/login?email=%s&password=%s" % (email, password)).read().split("\n")[0])
			if 'logged' == value:
				xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Login successfull')))
				for cookie in cookieJar:
					if cookie.name == 'PHPSESSID':
						self.__settings__.setSetting("auth", 'PHPSESSID=' + cookie.value)
			else:
				xbmc.executebuiltin("Notification(%s, %s [%s], 2500)" % (Localization.localize('Auth'), Localization.localize('Login failed'), value))
				self.loginUser()
		except urllib2.HTTPError, e:
			print self.__plugin__ + " loginUser() exception: " + str(e)
		xbmc.executebuiltin("Container.Refresh()")

	def registerUser(self, params = {}):
		if self.__settings__.getSetting("auth"):
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Already logged in')))
			return

		xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=False)
		keyboardUser = xbmc.Keyboard("", Localization.localize("Input Email (for password recovery):"))
		keyboardUser.doModal()
		email = keyboardUser.getText()
		if not email:
			return

		keyboardPass = xbmc.Keyboard("", Localization.localize("Input Password (6+ symbols):"))
		keyboardPass.setHiddenInput(True)
		keyboardPass.doModal()
		password = keyboardPass.getText()
		keyboardPass.setHiddenInput(False)
		if not password:
			return
		try:
			cookieJar = cookielib.CookieJar()
			opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
			value = json.loads(opener.open(self.URL + "/register?email=%s&password=%s" % (email, password)).read().split("\n")[0])
			if 'logged' == value:
				xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Login successfull')))
				for cookie in cookieJar:
					if cookie.name == 'PHPSESSID':
						self.__settings__.setSetting("auth", 'PHPSESSID=' + cookie.value)
			else:
				xbmc.executebuiltin("Notification(%s, %s [%s], 2500)" % (Localization.localize('Auth'), Localization.localize('Login failed'), value))
				self.loginUser()
		except urllib2.HTTPError, e:
			print self.__plugin__ + " registerUser() exception: " + str(e)
		xbmc.executebuiltin("Container.Refresh()")

	def logoutUser(self, params = {}):
		if not self.__settings__.getSetting("auth"):
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('User not logged in')))
			return
		self.__settings__.setSetting("auth", '')
		cookieJar = cookielib.CookieJar()
		opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
		opener.open(self.URL + "/logout").read()
		xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('User successfully logged out')))
		xbmc.executebuiltin("Container.Refresh()")

	def checkForAuth(self, response):
		if response == 'auth problems':
			xbmc.executebuiltin("Notification(%s, %s, 2500)" % (Localization.localize('Auth'), Localization.localize('Auth expired, please relogin')))
			time.sleep(2.5)
			self.logoutUser()
			return False
		return True
